package com.tinem.platform.service.message.api.group;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.nacos.common.util.HttpMethod;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.tinem.platform.module.pojo.enums.message.MqttMessageType;
import com.tinem.platform.module.pojo.vo.message.group.member.AddReq;
import com.tinem.platform.module.pojo.vo.message.group.member.DelReq;
import com.tinem.platform.module.pojo.vo.message.group.member.SetReq;
import com.tinem.platform.service.message.entity.MqttAcl;
import com.tinem.platform.service.message.repository.MqttAclRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@DS("emqx")
@RestController
@Api(value = "groupmember")
@RequestMapping("group/member/")
public class GroupMemberApi {

    @Value("${spring.profiles.active}")
    protected String active;

    @Resource
    MqttAclRepository mqttAclRepository;

    @PostMapping("add.api")
    @ApiOperation(value = "在群组内添加用户，如果用户已经存在则不处理。返回空字符串代表error", httpMethod = HttpMethod.POST, notes = "暂无")
    public Object add(@Validated @RequestBody AddReq addReq){
        try {
            String topic = MqttMessageType.GROUP.getGroupTopic(active, addReq.getGroupId());
            List<MqttAcl> mqttAclList = addReq.getMemberIds().stream()
                    .filter(m->mqttAclRepository.findTopByTopicAndUsername(topic,m)==null)
                    .map(m->{
                        MqttAcl mqttAcl = new MqttAcl();
                        mqttAcl.setAllow(1);
                        mqttAcl.setIpaddr(null);
                        mqttAcl.setUsername(m);
                        mqttAcl.setClientid(null);
                        mqttAcl.setAccess(1);
                        mqttAcl.setTopic(topic);
                        return mqttAcl;
                    }).collect(Collectors.toList());
            return mqttAclRepository.saveAll(mqttAclList).size();
        }catch (Exception e){
            log.info("",e);
        }
        return "";
    }

    @PostMapping("del.api")
    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    @ApiOperation(value = "在群组内删除用户，如果用户不存在则不处理。返回-1代表error。", httpMethod = HttpMethod.POST, notes = "暂无")
    public Integer del(@Validated @RequestBody DelReq delReq){
        try {
            return mqttAclRepository.deleteByTopicAndUsernameIn(MqttMessageType.GROUP.getGroupTopic(active, delReq.getGroupId()),delReq.getMemberIds());
        }catch (Exception e){
            log.info("",e);
        }
        return -1;
    }

    @PostMapping("set.api")
    @Transactional(value = Transactional.TxType.REQUIRED,rollbackOn = Exception.class)
    @ApiOperation(value = "设置群组内成员。如果MemberId为空，则删除群组，返回-1代表error", httpMethod = HttpMethod.POST, notes = "暂无")
    public Integer set(@Validated @RequestBody SetReq setReq){
        try {
            String topic = MqttMessageType.GROUP.getGroupTopic(active, setReq.getGroupId());
            int i = mqttAclRepository.deleteByTopic(topic);
            if(CollUtil.isEmpty(setReq.getMemberIds())){
                return 0;
            }
            List<MqttAcl> mqttAclList = setReq.getMemberIds().stream().map(m->{
                MqttAcl mqttAcl = new MqttAcl();
                mqttAcl.setAllow(1);
                mqttAcl.setIpaddr(null);
                mqttAcl.setUsername(m);
                mqttAcl.setClientid(null);
                mqttAcl.setAccess(1);
                mqttAcl.setTopic(topic);
                return mqttAcl;
            }).collect(Collectors.toList());
            return mqttAclRepository.saveAll(mqttAclList).size();
        }catch (Exception e){
            log.info("",e);
        }
        return -1;
    }
}
